package com.hmtech.ayp.business;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import com.hmtech.ayp.domain.dto.EditImageDTO;
import com.hmtech.ayp.domain.entity.Style;
import com.hmtech.ayp.service.IStyleService;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.Image;
import com.openai.models.images.ImageEditParams;
import com.openai.models.images.ImagesResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;

@Component
@Slf4j
public class ImageStyleTransformer {
    private final OpenAIClient client = OpenAIOkHttpClient.builder()
            .apiKey("sk-aBSir7qCZhRgpzP4E0722aC33c5247F4877eB9746fEe0729")
            .baseUrl("https://api.laozhang.ai/v1")
            .timeout(Duration.ofSeconds(100))
            .build();

    @Autowired
    private IStyleService styleService;

    public String transform(EditImageDTO request) throws IOException {
        Style style = styleService.getOneById(request.getStyleId());
        if (null == style) {
            throw new RuntimeException("Style not found");
        }
        File file = new File("C:\\Users\\11583\\Desktop\\girl.jpg");
        ImageEditParams params = ImageEditParams.builder()
                .model("gpt-image-1")
                .image(IoUtil.readBytes(new FileInputStream(file)))
                .quality(ImageEditParams.Quality.LOW)
                .prompt(style.getPrompt())
                .responseFormat(ImageEditParams.ResponseFormat.B64_JSON)
                .build();
        ImagesResponse resp = client.images().edit(params);
        if (resp.isValid()) {
            if (resp.data().isPresent() && CollectionUtil.isNotEmpty(resp.data().get())) {
                Image retImg = resp.data().get().get(0);
                if (retImg.b64Json().isPresent()) {
                    return retImg.b64Json().get();
                }
            }
        } else {
            log.error("Invalid response: " + resp);
        }
        log.error("编辑图片失败！返回空数据！请求：{}", request);
        return null;
    }
}
